<script setup lang="ts">
import officeApi from "@/api/office/officeApi";
import {TakeawayBox, SuitcaseLine, Suitcase} from '@element-plus/icons-vue'
import MindMap from 'simple-mind-map'
import MiniMap from 'simple-mind-map/src/plugins/MiniMap.js'
import Watermark from 'simple-mind-map/src/plugins/Watermark.js'
import KeyboardNavigation from 'simple-mind-map/src/plugins/KeyboardNavigation.js'
import ExportPDF from 'simple-mind-map/src/plugins/ExportPDF.js'
import ExportXMind from 'simple-mind-map/src/plugins/ExportXMind.js'
import Export from 'simple-mind-map/src/plugins/Export.js'
import Drag from 'simple-mind-map/src/plugins/Drag.js'
import Select from 'simple-mind-map/src/plugins/Select.js'
import RichText from 'simple-mind-map/src/plugins/RichText.js'
import AssociativeLine from 'simple-mind-map/src/plugins/AssociativeLine.js'
import TouchEvent from 'simple-mind-map/src/plugins/TouchEvent.js'
import NodeImgAdjust from 'simple-mind-map/src/plugins/NodeImgAdjust.js'
import SearchPlugin from 'simple-mind-map/src/plugins/Search.js'
import Painter from 'simple-mind-map/src/plugins/Painter.js'
import ScrollbarPlugin from 'simple-mind-map/src/plugins/Scrollbar.js'
import Formula from 'simple-mind-map/src/plugins/Formula.js'
import Cooperate from 'simple-mind-map/src/plugins/Cooperate.js'

// 注册插件
MindMap.usePlugin(MiniMap)
	.usePlugin(Watermark)
	.usePlugin(Drag)
	.usePlugin(KeyboardNavigation)
	.usePlugin(ExportPDF)
	.usePlugin(ExportXMind)
	.usePlugin(Export)
	.usePlugin(Select)
	.usePlugin(AssociativeLine)
	.usePlugin(NodeImgAdjust)
	.usePlugin(TouchEvent)
	.usePlugin(SearchPlugin)
	.usePlugin(Painter)
	.usePlugin(Formula)


const props = defineProps(["officeId","id"]);

// const container = ref();
const docValue = ref("");

// 当前右键点击的类型
const type = ref('')
// 如果点击的节点，那么代表被点击的节点
const currentNode = shallowRef(null)
// 是否显示菜单
const showContextMenu = ref(false);
// 菜单显示的位置
const menuPosition = ref({x: 0, y: 0});


const mindData = {
	"data": {
		"text": "Root Node",
	},
	"children": [
		{
			"data": {
				"text": "Child Node 1",
				"image": "",
				"imageTitle": "",
				"hyperlink": "",
				"note": ""
			},
			"children": []
		},
		{
			"data": {
				"text": "Child Node 2",
				"image": "",
				"imageTitle": "",
				"hyperlink": "",
				"note": ""
			},
			"children": []
		}
	]
};
const queryData = async () => {
	let data = await officeApi.getContentByOfficeId({
		officeId: props.officeId
	})

	if (!data) {
		data = {};
	}
	if (!data.content) {
		return {}
	}
	return JSON.parse(data.content);
}
const initWork = async () => {
	const data = await queryData();
	docValue.value = data;
	// workbook = univer.createUnit(UniverCore.UniverInstanceType.UNIVER_DOC, data)
}

onMounted(async () => {
	await initWork();
	initMindMap();

})
let mindMap = null;
const mindMapContainerRef = ref()
const initMindMap = () => {

	mindMap = new MindMap({
		el: mindMapContainerRef.value,
		data: {
			data: {
				"text": "根节点",
			}
		},
		editable: true, // 开启编辑模式
		mousewheelAction: 'move',// zoom（放大缩小）、move（上下移动）
		// 当mousewheelAction设为move时，可以通过该属性控制鼠标滚动一下视图移动的步长，单位px
		mousewheelMoveStep: 100,
		// 鼠标缩放是否以鼠标当前位置为中心点，否则以画布中心点
		mouseScaleCenterUseMousePosition: true,
		// 当mousewheelAction设为zoom时，或者按住Ctrl键时，默认向前滚动是缩小，向后滚动是放大，如果该属性设为true，那么会反过来
		mousewheelZoomActionReverse: true,
		// 禁止鼠标滚轮缩放，你仍旧可以使用api进行缩放
		disableMouseWheelZoom: false,
		layout: 'logicalStructure',
		// 连线的粗细
		lineWidth: 1,
		// 连线的颜色
		lineColor: '#549688',
		// 连线样式
		lineDasharray: 'none',
		// 连线风格，支持三种
		// 1.曲线（curve）。仅logicalStructure、mindMap、verticalTimeline三种结构支持。
		// 2.直线（straight）。
		// 3.直连（direct）。仅logicalStructure、mindMap、organizationStructure、verticalTimeline四种结构支持。
		lineStyle: 'curve',
		// 曲线连接时，根节点和其他节点的连接线样式保持统一，默认根节点为 ( 型，其他节点为 { 型，设为true后，都为 { 型。仅logicalStructure、mindMap两种结构支持。
		rootLineKeepSameInCurve: true,
		// 直线连接(straight)时，连线的圆角大小，设置为0代表没有圆角，仅支持logicalStructure、mindMap、verticalTimeline三种结构
		lineRadius: 5,
		// 连线尾部是否显示标记，目前只支持箭头
		showLineMarker: false,
		// 概要连线的粗细
		generalizationLineWidth: 1
	});
	if (docValue.value) {
		mindMap.setFullData(docValue.value);

	}

	mindMap.on('node_contextmenu', (e, node) => {
		if (e.which == 3) {
			menuPosition.value = {x: e.clientX + 10, y: e.clientY + 10};
			showContextMenu.value = true;
			currentNode.value = node
		}
	})
	// 点击空白处
	mindMap.on('node_click', hide)
	mindMap.on('draw_click', hide)
	mindMap.on('expand_btn_click', hide)
	// mindMap.value.setFullData(mindData);

}


const saveContent = () => {
	let data = getValue();

	officeApi.saveContent({
		officeId: props.officeId,
		content: JSON.stringify(data),
		fileTypeCode: "mind"
	});

}
// 隐藏右侧菜单
const hide = () => {
	menuPosition.value = {x: 0, y: 0};
	showContextMenu.value = false;
	currentNode.value = null
}
const getValue = () => {
	// console.log(workbook)
	// const saveData = workbook.save();
	// const c = wordEditor.value.getValue();
	// return c;
	const data = mindMap.getData(true)
	return data;
	// return saveData;
}

// 添加节点
const addChildNode = () => {
	if (mindMap) {
		mindMap.execCommand('INSERT_CHILD_NODE')
	}
	showContextMenu.value = false; // 关闭菜单
};

// 添加同级节点
const addSameNode = () => {
	if (mindMap) {
		mindMap.execCommand('INSERT_NODE')
	}
	showContextMenu.value = false; // 关闭菜单
};
// 删除节点
const removeNode = () => {
	if (mindMap && currentNode.value) {
		mindMap.execCommand('REMOVE_NODE')
	}
	showContextMenu.value = false; // 关闭菜单
};

// 复制节点
const copyNode = () => {
	if (mindMap && currentNode.value) {
		mindMap.renderer.copy()
	}
	showContextMenu.value = false; // 关闭菜单
};

// 粘贴节点
const pasteNode = () => {
	if (mindMap && currentNode.value) {
		mindMap.renderer.paste()
	}
	showContextMenu.value = false; // 关闭菜单
};

// 导出为图片
const exportMindMap = () => {
	if (mindMap) {
		mindMap.export('png', true, '底格里斯任务中心图')
	}
};

const saveMindMap = () => {
	if (mindMap) {
		mindMap.export('xmind', true, '底格里斯任务中心图')
	}
};

defineExpose({
	getValue
})

</script>

<template>
	<!-- vue3-mindmap https://github.com/hellowuxin/vue3-mindmap  -->
	<div style="height:100%;">
		<div id="mindMapContainer" ref="mindMapContainerRef" style="height: 100%;"></div>

		<div class="top-menu-fixed" v-if="props.id">
			<a-space>
				<div class="top-menu-item" @click="saveMindMap">
					<a-button>导出xmind</a-button>
				</div>
				<div class="top-menu-item" @click="saveContent">
					<a-button type="primary">提交</a-button>
				</div>
				<div class="top-menu-item" @click="exportMindMap">
					<a-button>导出图片</a-button>
				</div>
			</a-space>
		</div>

		<!-- 右键菜单 -->
		<div v-if="showContextMenu" class="context-menu"
			 :style="{ top: `${menuPosition.y}px`, left: `${menuPosition.x}px` }">
			<ul>
				<li @click="addChildNode">添加子节点</li>
				<li @click="addSameNode">添加同级节点</li>
				<li @click="removeNode">删除节点</li>
				<li @click="copyNode">复制节点</li>
				<li @click="pasteNode">粘贴节点</li>
			</ul>
		</div>
	</div>
</template>

<style scoped>
#mindMapContainer * {
	margin: 0;
	padding: 0;
}

.top-menu-fixed {
	position: absolute;
	top: 50px;
	left: 60%;
	width: 300px;
	z-index: 1000;
	display: flex;
	justify-content: space-around;
	background-color: #fff;
	padding: 10px 20px;
	border-radius: 6px;
	box-shadow: 0 2px 16px 0 rgba(0, 0, 0, .06);
	border: 1px solid rgba(0, 0, 0, .06);
	margin-right: 20px;
}

.context-menu {
	position: fixed;
	background-color: white;
	border: 1px solid #ccc;
	box-shadow: 0px 2px 10px rgba(0, 0, 0, 0.1);
	z-index: 1000;
	padding: 10px;
	border-radius: 4px;
}

.context-menu ul {
	list-style: none;
	padding: 0;
	margin: 0;
}

.context-menu li {
	padding: 8px 12px;
	cursor: pointer;
}

.context-menu li:hover {
	background-color: #f0f0f0;
}

</style>
